package me.xpyex.plugin.fixprimordialpearl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import java.io.ByteArrayOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

public class CheckUpdate implements Listener {
    public static final String PLUGIN_VERSION = FixPrimordialPearl.INSTANCE.getDescription().getVersion();
    private static final String PREFIX = ChatColor.LIGHT_PURPLE + "[FixPrimordialPearl] ";
    public static String newVer;

    public static void checkUpdate() {
        Bukkit.getScheduler().runTaskAsynchronously(FixPrimordialPearl.INSTANCE, () -> {
            try {
                HttpURLConnection huc = (HttpURLConnection) new URL("https://gitee.com/api/v5/repos/xpyex/FixPrimordialPearl/tags").openConnection();
                huc.setRequestMethod("GET");
                huc.connect();
                ByteArrayOutputStream ba = new ByteArrayOutputStream(16384);
                int nRead;
                byte[] data = new byte[4096];
                while ((nRead = huc.getInputStream().read(data, 0, data.length)) != -1) {
                    ba.write(data, 0, nRead);
                }
                JsonArray array = new Gson().fromJson(ba.toString("UTF-8"), JsonArray.class);
                JsonObject latestVer = array.get(array.size() - 1).getAsJsonObject();
                String name = latestVer.get("name").getAsString();
                if (!name.equals("v" + PLUGIN_VERSION)) {
                    FixPrimordialPearl.LOGGER.info("服务器当前运行的插件版本为: v" + PLUGIN_VERSION);
                    FixPrimordialPearl.LOGGER.info("找到一个更新的版本: " + name);
                    newVer = name;
                    FixPrimordialPearl.LOGGER.info("下载地址: https://gitee.com/xpyex/FixPrimordialPearl/releases");
                    Bukkit.getPluginManager().registerEvents(new CheckUpdate(), FixPrimordialPearl.INSTANCE);
                    //获取到更新才注册监听器，节省资源
                } else {
                    FixPrimordialPearl.LOGGER.info("您当前运行的插件为最新版");
                }
            } catch (Exception e) {
                FixPrimordialPearl.LOGGER.info("检查更新失败");
                e.printStackTrace();
            }
        });
    }

    @EventHandler
    public void onJoin(PlayerJoinEvent event) {
        if (event.getPlayer().hasPermission("op")) {  //不用isOp是因为某些权限组不允许存在OP
            event.getPlayer().sendMessage(PREFIX + ChatColor.AQUA + "服务器当前运行的插件版本为: " + ChatColor.RESET + "v" + CheckUpdate.PLUGIN_VERSION);
            event.getPlayer().sendMessage(PREFIX + ChatColor.GREEN + "找到一个更新的版本: " + ChatColor.RESET + CheckUpdate.newVer);
            TextComponent msg = new TextComponent(PREFIX + ChatColor.GOLD + "点我打开下载界面" + ChatColor.GRAY + ChatColor.ITALIC + "(Gitee)");
            msg.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, "https://gitee.com/xpyex/FixPrimordialPearl/releases"));
            event.getPlayer().spigot().sendMessage(msg);

        }
    }
}
